<template>
  <list-detail-layout :col-props="{ md: [7, 17] }" :right-bg-color="'#fff'" class="editCarModelLayout">
    <template #detailMain>
      <div class="editVehicleLeftBox h100">
        <div style="padding: 20px 10px 20px 10px" v-if="!vehicleId || (vehicleId && editCode=='UNKNOWN')">
          <a-input-search
            v-model="carModelKey"
            :placeholder="$t('modelNameOrCode')"
            style="width: 100%"
            allowClear
            size="small"
            @change="onSearch"
            @search="search"
          />
        </div>
        <full-parent-dom-with-dask :loading="loadingModelsData"></full-parent-dom-with-dask>
        <ul class="carModelBox" style="height: calc(100% - 32px)">
          <li
            class="carModelItem"
            :class="{ active: formData.modelId === model.id }"
            v-for="model in models"
            :key="model.id"
            @click="toggleModel(model.id,model.code)"
          >
            <p class="carModelTitle">
              <i class="iconfont icon-chexing1"></i>
              <span>{{ model.name }}</span><span v-if="model.code"> | {{ model.code }}</span>
            </p>
            <!-- <p class="carModelDesc"> -->
              <!-- <span v-if="model.code">{{ model.code || '-' }}</span> -->
              <!-- <span class="divider" v-if="model.trimLevel">|</span>
              <span v-if="model.trimLevel">{{ model.trimLevel || '-' }}</span> -->
            <!-- </p> -->
          </li>
          <li class="carModelItem" v-if="loadingModelsData === false && models.length === 0">{{ $t('noData') }}</li>
        </ul>
        
      </div>
    </template>
    <template #detailRight>
      <!-- 填写车辆基本信息、显示车型信息、车型零件区域 -->
      <div class="editVehicleRightBox h100" :style="{'opacity' : loadingVehicleFormData ? 0.3 : 1}">
        <!-- 显示车型信息start -->
        <div class="showCarModelInfo">
          <h4 class="withVerticleLineT4 title14">
            {{ $t('carModelInfo') }}
            <span class="warning" v-if="!formData.modelId && loadingCarModelInfoData === false">
              ({{ $t('pleaseSelect') + $t('vehicleModelMenu').toLowerCase() }})
            </span>
            <!-- 展开与折叠 -->
            <span
              class="arrow"
              @click="toggleShow('modelInfo')"
            >{{ $t(showConfig.modelInfo ? 'packup' : 'packdown') }}
              <a-icon type="right" :class="{ down: showConfig.modelInfo }" />
            </span>
          </h4>
          <div class="descItems" v-show="showConfig.modelInfo">
            <full-parent-dom-with-dask :loading="loadingCarModelInfoData"></full-parent-dom-with-dask>
            <div class="descItemOneBox">
              <div class="descItem">
                <span class="descTitle">{{ $t('modelName') }}</span>
                <span class="descValue">
                  <table-ellipsis
                    :tableEllipsisIsTurnLine="false"
                    :text="activeCarModelInfo.name || '-'"
                  ></table-ellipsis>
                </span>
              </div>
              <div class="descItem">
                <span class="descTitle">{{ $t('brandName') }}</span>
                <span class="descValue">
                  <table-ellipsis
                    :tableEllipsisIsTurnLine="false"
                    :text="activeCarModelInfo.brandName || '-'"
                  ></table-ellipsis>
                </span>
              </div>
            </div>
            <div class="descItemTwoBox">
              <div class="descItem">
                <span class="descTitle">{{ $t('modelCode') }}</span>
                <span class="descValue">
                  <table-ellipsis
                    :tableEllipsisIsTurnLine="false"
                    :text="activeCarModelInfo.code || '-'"
                  ></table-ellipsis>
                </span>
              </div>
              <div class="descItem">
                <span class="descTitle">{{ $t('销售区域') }}</span>
                <span class="descValue">
                  <table-ellipsis
                    :tableEllipsisIsTurnLine="false"
                    :text="$store.getters.getDictCodeObj('saleAreaDictCode')[activeCarModelInfo.saleArea] || '-'"
                  ></table-ellipsis>
                </span>
              </div>
            </div>
            <div class="descItemThreeBox">
              <div class="descItem">
                <span class="descTitle">品牌</span>
                <span class="descValue">
                  <table-ellipsis
                    :tableEllipsisIsTurnLine="false"
                    :text="$store.getters.getDictCodeObj('companyDictCode')[activeCarModelInfo.company] || '-'"
                  ></table-ellipsis>
                </span>
              </div>
            </div>
          </div>
        </div>
        <!-- 显示车型信息end -->
        <!-- 款型配置start -->
        <h4 class="withVerticleLineT4 title14">
          {{ $t('款型配置') }}
        </h4>
        <a-form-model
          ref="formComp"
          :model="formData"
          :rules="rules"
          layout="horizontal"
          class="AsteriskAfter newEditStyle editVehicleBaseInfo"
        >
          <full-parent-dom-with-dask :loading="loadingVehicleFormData"></full-parent-dom-with-dask>
          <a-row :gutter="20">
            <a-col :md="12" :sm="24">
              <a-form-model-item label="子车型代码" prop="code">
                <a-input :maxLength="15" v-model="formData.code" :disabled="Boolean(formData.id && initformData.code!='未知')" />
              </a-form-model-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-model-item label="配置车型代码" prop="configModelCode">
                <a-input :maxLength="15" v-model="formData.configModelCode" :disabled="Boolean(formData.id && initformData.configModelCode!='未知')" />
              </a-form-model-item>
            </a-col>
<!--          </a-row>-->
<!--          <a-row :gutter="20">-->
            <a-col :md="12" :sm="24">
              <a-form-model-item label="款型名称" prop="name">
                <a-input :maxLength="20" v-model="formData.name" :disabled="Boolean(formData.id && initformData.name!='未知')" />
              </a-form-model-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-model-item label="公告车型" prop="publishCode">
                <a-input :maxLength="20" v-model="formData.publishCode" :disabled="Boolean(formData.id && initformData.publishCode!='未知')" />
              </a-form-model-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-model-item label="车型ID" prop="bizModelId">
                <a-input :maxLength="15" v-model="formData.bizModelId" :disabled="Boolean(formData.id && initformData.bizModelId!='未知')" />
              </a-form-model-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-model-item label="年款" prop="makeYear">
                <a-input :maxLength="10" v-model="formData.makeYear" :disabled="Boolean(formData.id)" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <div style="fontWeight:600">生产配置</div>
          <a-row :gutter="20">
            <a-col :md="12" :sm="24" >
              <a-form-model-item label="生产车系" prop="productionSeries">
                <a-input :maxLength="20" v-model="formData.productionSeries" :disabled="Boolean(formData.id)" />
              </a-form-model-item>
            </a-col>
            <a-col :md="12" :sm="24" >
              <a-form-model-item label="生产车型" prop="productionModel">
                <a-input :maxLength="100" v-model="formData.productionModel" :disabled="Boolean(formData.id)" />
              </a-form-model-item>
            </a-col>
          </a-row>
          
          <!-- 基本信息end -->
        </a-form-model>
        <!-- 款型配置end -->
        <!-- 显示车型零件信息start -->
        <div class="showCarPartInfo">
          <h4 class="withVerticleLineT4 title14">
            {{ $t('carModelPart') }}
            <!-- <span class="warning">
              ({{ $t('请配置ECU信息') }})
            </span> -->
            <span
              class="arrow"
              @click="toggleShow('modelParts')"
            >{{ $t(showConfig.modelParts ? 'packup' : 'packdown') }}
              <a-icon type="right" :class="{ down: showConfig.modelParts }" />
            </span>
          </h4>
          <div class="commonTableSty" v-show="showConfig.modelParts">
            <a-table
              :columns="columns"
              :data-source="activeCarPartTbData"
              :loading="loadingCarModelPartLists"
              :pagination="false"
              :scroll="{ x: 800, y: 200 }"
              ref="table"
            >
              <template slot-scope="text" v-for="column in commonColumns" :slot="column.scopedSlots.customRender">
                <table-ellipsis :text="text || '-'" :key="column.dataIndex"></table-ellipsis>
              </template>
              <!-- <template slot-scope="text" slot="ecuConfig">
                <a-select v-model="config" @change="changeConfig" allow-clear>
                  <a-select-option v-for="item in formsStatusArr" :key="item.value" :value="item.value">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </template> -->
            </a-table>
          </div>
        </div>
        
      </div>
    </template>
  </list-detail-layout>
</template>
<script>
import FullParentDomWithDask from '@/components/LoadDataSpin/FullParentDomWithDask.vue'
import TableEllipsis from '@/components/Ellipsis/TableEllipsis'
import RoleSelect from '@/views/components/RoleSelect'
import VehicleTypeSelect from '@/views/components/VehicleTypeSelect'
import VehicleModelSelect from '@/views/components/VehicleModelSelect'
import ProvinceSelect from '@/views/components/ProvinceSelect'
import ListDetailLayout from '@/views/components/ListDetailLayout.vue'
import { mapState } from 'vuex'
import { modelStyleFormInitData } from '../config/form'
import { ecuTbColumns } from '../config/list'
import carModelApi from '@/api/modules/system/modelMana'
import ecuApi from '@/api/modules/system/ecuMana'
import vehicleApi from '@/api/modules/system/vehicleMana'
import moment from 'moment'
import lodash from 'lodash'
import { STable } from '@/components'
import { checkTextLen } from '@/utils/validate'
export default {
  name: 'NewEditModel',
  components: {
    RoleSelect,
    VehicleTypeSelect,
    VehicleModelSelect,
    ProvinceSelect,
    ListDetailLayout,
    FullParentDomWithDask,
    TableEllipsis,
    STable
  },
  props: {
    nowTime: {
      type: Number,
      default: 1
    },
    copyId: {
      type: String,
      default: ''
    },
    vehicleId: {
      type: String,
      default: ''
    },
    initVehicleType: {
      type: Number,
      default: undefined
    }
  },
  computed: {
    ...mapState({
      ProducePhase: (state) => state.dict.producePhaseDictCode,
      Manufacturer: (state) => state.dict.manufacturerDictCode,
      saleArea: (state) => state.dict.saleAreaDictCode,
      roles: (state) => state.role.roleData
    }),
    commonColumns () {
      return this.columns.filter((item) => !item.special)
    }
  },
  data () {
    const _this = this
    return {
      formData: {...lodash.clone(modelStyleFormInitData),vehicleType: _this.initVehicleType},
      initformData: {},
      rules: {
        code: [{ required: true, message: this.$t('pleaseInput') }],
        configModelCode: [{ required: true, message: this.$t('pleaseInput') }],
        publishCode: [{ required: true, message: this.$t('pleaseInput') }],
        makeYear: [{ message: this.$t('pleaseInput') }],
        bizModelId: [{ required: true, message: this.$t('pleaseInput') }],
        name: [{ required: true, message: this.$t('pleaseInput') }],
        productionSeries: [{ required: true, message: this.$t('pleaseInput') }],
        productionModel: [{ required: true, message: this.$t('pleaseInput') }]
      },
      time: 1100,
      columns: ecuTbColumns,
      treeData: [],
      loadingModelsData: false,
      loadingCarModelInfoData: false,
      activeCarModelInfo: {},
      loadingCarModelPartLists: false,
      activeCarPartTbData: [],
      loadingVehicleFormData: false,
      models: [{ id: 111, name: 'def' }],
      showConfig: {
        modelInfo: true,
        modelParts: true
      },
      carModelKey: '',
      editCode:''
    }
  },
  watch: {
    nowTime: {
      handler () {
        // this.init();
      },
      immediate: true
    },
    'formData.modelId': {
      handler (val) {
        if (val) {
          this.getActiveCarModelInfoData()
          this.getActiveCarModelTbData()
        } else {
          !this.formData.id && this.resetFields()
        }
      },
      immediate: true
    }
  },

  created () {
    this.init(true);
    this.$store.dispatch('getProducePhaseDictCodeData');
    this.$store.dispatch('getManufacturerDictCodeData');
    this.$store.dispatch('getDiLinkVersionDictCodeData');
    this.$store.dispatch('getSaleAreaDictCodeData');
    this.$store.dispatch('getCompanyDictCodeData');
  },
  methods: {
    init(reset = false) {
      this.carModelKey = ''
      this.getModelsData()
      if(reset){
        this.getModelStyleFormData()
      }
    },
    disabledDate (current) {
      return current > moment()
    },
    onChangeDate (val, dateString) {
      this.formData.productionTime = dateString
    },
    changeOption (val, key) {
      const vm = this
      vm.$set(vm.formData, key, val)
      vm.$refs.formComp.validateField(key)
    },
    resetFields () {
      this.activeCarPartTbData = []
      this.activeCarModelInfo = {}
      this.formData = {...lodash.clone(modelStyleFormInitData),vehicleType: this.initVehicleType}
      this.$refs.formComp && this.$refs.formComp.clearValidate()
    },
    getFormData () {
      if(this.activeCarModelInfo.code=='UNKNOWN'){
        this.$message.error('请选择车型')
        return 
      }
      return new Promise((resolve, reject) => {
        const data = this.formData
        if (!this.otherCheck()) {
          return
        }
        this.$refs.formComp.validate((valid) => {
          if (!valid) {
            reject(valid)
          }
          resolve(data)
        })
      })
    },
    otherCheck () {
      const msg = this.$t('pleaseInput')
      if (!this.formData.modelId) {
        this.$message.error(msg + this.$t('vehicleModel'))
        return false
      }
      return true
    },
    // 获取车型数据
    getModelsData () {
      this.models = []
      // this.formData.modelId = ''
      this.loadingModelsData = true
      carModelApi
        .getMyAllModel({ searchWord: this.carModelKey })
        .then((res) => {
          this.models = res.data
        })
        .finally(() => {
          this.loadingModelsData = false
        })
    },
    toggleModel (modelId,modelCode) {
      if (modelId === this.formData.modelId) {
        return
      }
      if (modelCode=='UNKNOWN'){
        this.$message.error('不可选择未知车型')
        return
      }
      if(this.vehicleId && this.editCode=='UNKNOWN'){
        this.formData.modelId = modelId
        return
      }
      // 修改时不能修改车型id
      if (this.vehicleId) {
        this.$message.error(this.$t('编辑款型时不能修改车型'))
        return
      }
      this.formData.modelId = modelId
    },

    // 获取当前车型信息
    getActiveCarModelInfoData () {
      this.activeCarModelInfo = {}
      this.loadingCarModelInfoData = true
      carModelApi
        .getModelDetail({ id: this.formData.modelId })
        .then((res) => {
          this.activeCarModelInfo = res.data
          console.log(this.activeCarModelInfo, 'this.activeCarModelInfo')
        })
        .finally(() => {
          this.loadingCarModelInfoData = false
        })
    },
    // 获取当前车型零件列表
    getActiveCarModelTbData () {
      this.activeCarPartTbData = []
      this.loadingCarModelPartLists = true
      ecuApi
        .getEcuList({ modelId: this.formData.modelId, pageSize: 9999 })
        .then((res) => {
          this.activeCarPartTbData = res.data
        })
        .finally(() => {
          this.loadingCarModelPartLists = false
        })
    },
    // 获取当前车辆表单编辑的信息
    getModelStyleFormData () {
      this.resetFields()
      if (!this.vehicleId && !this.copyId) {
        this.formData.vehicleType = this.initVehicleType;
        return
      }
      this.loadingVehicleFormData = true
      this.formData.id = this.vehicleId
      this.$api
        .getModelStyleDetail( this.vehicleId || this.copyId )
        .then((res) => {
          const info = res.data
          this.formData.modelId=info.model.id
          this.formData.code=info.code
          this.formData.configModelCode=info.configModelCode
          this.formData.name=info.name
          this.formData.publishCode=info.publishCode
          this.formData.bizModelId=info.bizModelId
          this.formData.makeYear=info.makeYear
          this.formData.productionSeries=info.productionSeries
          this.formData.productionModel=info.productionModel
          this.initformData={...this.formData}
          this.editCode=info.model.code
        })
        .finally(() => {
          this.loadingVehicleFormData = false
        })
    },
    toggleShow (key) {
      this.showConfig[key] = !this.showConfig[key]
    },
    onSearch: lodash.debounce(function () {
      this.search()
    }, 300),
    search () {
      this.getModelsData()
    }
  }
}
</script>
<style lang="less" scoped>
.ant-form-item {
  height: 75px;
  margin-bottom: 0;
  /*&:has(.has-error){*/
  /*  margin-bottom: -3px;*/
  /*}*/
}
.editVehicleLeftBox {
  // overflow: auto;
  // position: relative;

  .arrowRightDown {
    transition: all 0.3s;
  }

  .icon-xiangmuguanli {
    margin: 0 5px;
  }

  .carModelBox {
     overflow: auto;
    position: relative;
    .carModelItem {
      padding: 10px 20px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      cursor: pointer;
      color: #000000a6;

      &:hover {
        background-color: @blockHoverBgColor;
        color: @blockHoverTextColor;
      }

      &.active {
        color: @blockHoverTextColor;
      }

      .icon-chexing1 {
        margin-right: 5px;
      }

      .carModelDesc {
        font-size: 0.8em;
        margin-top: 5px;
      }

      .divider {
        margin: 0 5px;
      }
    }
  }
}

.editVehicleRightBox {
  .title14 {
    margin-bottom: 15px;
    position: relative;

    .arrow {
      position: absolute;
      right: 0;
      top: 3px;
      color: @primary-color;
      font-size: 0.9em;
      cursor: pointer;
      font-weight: 500;

      .anticon {
        padding-left: 3px;
        transition: all 0.3s;

        &.down {
          transform: rotate(90deg);
        }
      }
    }
  }

  .warning {
    color: #f5222d;
  }

  .editVehicleBaseInfo {
    position: relative;
  }

  .showCarModelInfo {
    position: relative;
    padding-bottom: 15px;
  }

  .descItems {
    display: flex;

    .descItemOneBox {
      flex: 36% 0 0;
    }

    .descItemTwoBox {
      flex: 38% 0 0;
    }

    .descItemThreeBox {
      flex: 22% 0 0;
    }

    .descItem {
      padding: 5px 0;
      font-size: 0.9em;
      display: flex;
    }

    .descTitle {
      font-weight: bold;
      flex: 100px 0 0;
    }

    .descValue {
      flex: 1 0 0;
      font-size: 1em;
    }
  }

  .showCarPartInfo {
    border-top: 1px solid @borderColor;
    padding: 15px 0;
  }
}
</style>
<style lang="less">
.editCarModelLayout {
  .drawerListDetailLeft {
    padding: 15px 0px 40px 20px !important;
  }
}
</style>
